//
//  NetworkTools.swift
//  MyMicroBlog
//
//  Created by H on 15/8/2.
//  Copyright © 2015年 H. All rights reserved.
//

import UIKit
import  AFNetworking
/// 错误的类别标记
private let HMErrorDomainName = "com.itheima.error.network"
//枚举封装错误信息
private  enum HMNetworkError:Int {

     case emptyDataError = -1
    case emptyTokenError = -2
    private var errorDescription :String {
        switch self {
        case.emptyDataError :return "空数据"
        case.emptyTokenError:return "Token为空"
        }
    }
        private func error()->NSError {
        
        
            return NSError(domain: HMErrorDomainName, code: rawValue, userInfo: [HMErrorDomainName:errorDescription])
        
        }
    
}
//网络方法
private enum HMNetworkMethod : String {
    case GET = "GET"
    case POST = "POST"
}

class NetworkTools: AFHTTPSessionManager{
    private var clientID = "4260433006"
    private  var appSecret = "321c08526737e08a1783fdff4d6f2fef"
    var redirectUrl = "http://www.baidu.com"
    //MARK:- 封装网络方法
    typealias HMNetFinishedCallBack = (result: [String: AnyObject]?, error: NSError?)->()
    //建立一个单例的全局访问点
   
    static let sharedNetworkTools:NetworkTools = {
    let instance = NetworkTools(baseURL: NSURL(string: "https://api.weibo.com/")!)
        instance.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript", "text/plain") as Set<NSObject>

    return instance
    
    }()
    //MARK:-检查Token是否存在,并生成token字典
    private func tokenDict(finished:HMNetFinishedCallBack)->[String: AnyObject]?  {
        // 判断 token 是否存在
        if UserAccount.sharedUserAccount?.access_token == nil {
            // 错误回调，token 为空
            let error = HMNetworkError.emptyTokenError.error()
            
            print(error)
            finished(result: nil, error: error)
            
            return nil
        }

        return ["access_token": UserAccount.sharedUserAccount!.access_token!]
    
    }
    
    
    
    //MARK:-加载微博数据
    func loadStatus(since_id: Int, max_id: Int, finished: HMNetFinishedCallBack) {
        
        guard var params = tokenDict(finished) else {
            return
        }
        
        if since_id > 0 {
            params["since_id"] = since_id
        }
        if max_id > 0 {
            params["max_id"] = max_id - 1
        }
        
        // 代码运行至此，params 一定有值
        let urlString = "2/statuses/home_timeline.json"
        
        request(HMNetworkMethod.GET, urlString: urlString, params: params, finished: finished)
    }
    
    
    
    //MARK:-加载用户数据
    func loadUserInfo(uid:String,finished:HMNetFinishedCallBack){
        guard var params = tokenDict(finished) else {
        return
        }
        let urlString = "2/users/show.json"
        params["uid"] = uid
        request(HMNetworkMethod.GET, urlString: urlString, params: params, finished: finished)
    }

    //MARK:-授权URL
    var oauthURL : NSURL {
    
    return NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(clientID)&redirect_uri=\(redirectUrl)")!
    
    }
    //MARK:-加载token
//    获取授权	oauth2/access_token	获取授权过的Access Token
    
/* 
    参数:  client_id	true	string	申请应用时分配的AppKey。
   client_secret	true	string	申请应用时分配的AppSecret。
    grant_type	true	string	请求的类型，填写authorization_code
    code	true	string	调用authorize获得的code值。
    redirect_uri	true	string	回调地址，需需与注册应用里的回调地址一致。
*/

    func loadAccessToken(code:String,finished: HMNetFinishedCallBack) {
    let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id":clientID,
            "client_secret":appSecret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":redirectUrl]
        request(HMNetworkMethod.POST, urlString: urlString, params: params, finished: finished)

    }
 
    /**
    AFN网络请求 GET/POST
    :param: method    HTTP方法
    :param: urlString URL字符串
    :param: params    字典参数
    :param: finished  完成回调
    */
    private func request(method:HMNetworkMethod, urlString: String, params: [String: AnyObject], finished: HMNetFinishedCallBack){
    //成功的闭包
        let successCallBack:(NSURLSessionDataTask!, AnyObject!) -> Void = {
            (_ , JSON) -> Void in
            if let result = JSON as? [String: AnyObject] {
                // 有结果的回调
                finished(result: result, error: nil)
            } else {
                
                finished(result: nil, error: HMNetworkError.emptyDataError.error())
              }
        }
            //失败的闭包
            let failedCallBack: (NSURLSessionDataTask!, NSError!) -> Void = { (_, error) -> Void in
                print(error)
                
                finished(result: nil, error: error)
            }
        //根据method来选择执行的方法
        switch method {
        
        case .GET:
            GET(urlString, parameters: params, success: successCallBack, failure: failedCallBack)
        case .POST:
            POST(urlString, parameters: params, success: successCallBack, failure:failedCallBack)
      
        }
    
    }
    

   
}
